package com.taotao.util;


import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import org.apache.commons.io.IOUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;

@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class FileDownUtils {

    /**
     * 文件扩展名多个用|隔开,*表示所有
     */
    public static final String FILE_EXT_SEPARATOR = "|";
    public static final String FILE_EXT_ALL = "*";


    public static final long KB = 1024;
    public static final long MB = KB * 1024;
    public static final long GB = MB * 1024;
    public static final long TB = GB * 1024;
    public static final long PB = TB * 1024;


    /**
     * 下载文件
     *
     * @param is               文件输入流
     * @param fileName         下载文件名称
     * @param response
     * @param closeInputStream 是否关闭
     * @throws IOException
     */
    public static void downFile(InputStream is, String fileName, HttpServletResponse response, boolean closeInputStream) throws IOException {
        try {
            response.setContentType("application/octet-stream");
            response.setCharacterEncoding("UTF-8");
            response.addHeader("Content-Length", is.available() + "");
            response.addHeader("Content-Disposition", "attachment; filename=\"" + URLEncoder.encode(fileName, "UTF-8") + "\"");
            // 这里response.getOutputStream()不需要关闭，由servlet容器关闭
            IOUtils.copy(is, response.getOutputStream());
        } finally {
            if (closeInputStream) {
                is.close();
            }
        }
    }


    /**
     * 下载文件
     *
     * @param is       文件输入流,用完会关闭
     * @param fileName 下载文件名称
     * @param response
     * @throws IOException
     */
    public static void downFile(InputStream is, String fileName, HttpServletResponse response) throws IOException {
        downFile(is, fileName, response, true);
    }


}
